import { defineStore } from "pinia";
import { router } from "@/router";
import { getMenuList } from "@/api/meun";
import _ from "lodash";
import { useSecureStorage } from "@/util/cryptoData";
const { secureSetItem, secureGetItem, secureRemoveItem } = useSecureStorage();
export const useUserStore = defineStore("user", {
  state() {
    return {
      token: localStorage.getItem("token") || "",
      refreshToken: localStorage.getItem("refreshToken") || "",
      menuList: [] as Array<any>,
      latestMenuList: [] as Array<any>,
      tabs: [
        {
          key: "666",
          label: "首页",
          path: "/index",
          icon: "House",
          closeable: false,
        },
      ],
      activeMenu: "666",
      activeTab: "666",
      collsapTop: 50,
      collsapMenu: [],
      isMouseOverChild: false,
      hoveredMenu: null,
      expandedMenus: "666",
      selectDirMenu: [], //添加菜单时可选目录菜单
      user_info: secureGetItem("user_info") || {}, //用户信息,
    };
  },
  getters: {
    authToken: (state) => state.token,
    refreshAuthToken: (state) => state.refreshToken,
    dirMenu: (state) => state.selectDirMenu,
    flattenMenu: (state) => {
      function flattenArray(arr: any) {
        let result: any[] = [];
        arr.forEach((item: any) => {
          // 添加当前项（不包括children属性）
          const tempData = _.cloneDeep(item);
          delete tempData.children;
          result.push(tempData);
          // 如果有children，则递归处理
          if (item.children && item.children.length > 0) {
            result = result.concat(flattenArray(item.children));
          }
        });
        return result;
      }
      return flattenArray(state.menuList);
    },
  },
  actions: {
    clearUserInfo() {
      this.user_info = {}; // 清空 user_info 状态
      secureRemoveItem("user_info"); // 使用安全存储方法清除用户信息
    },
    setUserInfo(data: any) {
      this.user_info = data;
      secureSetItem("user_info", this.user_info); // 使用安全存储方法保存用户信息
    },
    setToken(token: string) {
      this.token = token;
      // 当设置 token 时，也保存到 localStorage
      localStorage.setItem("token", this.token);
    },
    setRefreshToken(refreshToken: string) {
      this.refreshToken = refreshToken;
      localStorage.setItem("refreshToken", this.refreshToken);
    },
    clearToken() {
      this.token = "";
      // 清除 localStorage 中的 token
      localStorage.removeItem("token");
    },
    cleanRefreshToken() {
      this.refreshToken = "";
      // 清除 localStorage 中的 refreshToken
      localStorage.removeItem("refreshToken");
    },
    setDirMenu(data: any) {
      this.selectDirMenu = _.cloneDeep(data);
    },
    setcollsapTop(data: any) {
      this.collsapTop = data;
    },
    setCollsapMenu(data: any) {
      this.collsapMenu = _.cloneDeep(data);
    },
    setIsMouseOverChild(data: any) {
      this.isMouseOverChild = data;
    },
    setExpandedMenus(data: any) {
      this.expandedMenus = data;
    },
    setActiveMenu(data: any) {
      this.activeMenu = data;
    },
    setTabs(data: any) {
      this.tabs.push(_.cloneDeep(data));
    },
    setActiveTab(data: any) {
      this.activeTab = data;
    },
    switchTab(data: any) {
      router.push(data.path);
    },
    closeTab(index: any) {
      if (this.tabs[index].key === this.activeTab) {
        const tab = this.tabs[index - 1];
        this.tabs.splice(index, 1);
        router.push(tab.path);
      } else {
        this.tabs.splice(index, 1);
      }
    },
    closeAllTabs() {
      // 只保留首页
      this.tabs = this.tabs.filter((tab) => tab.key === "666");
      this.activeTab = "666";
      router.push("/index");
    },
    closeLeftTabs() {
      const activeIdx = this.tabs.findIndex(
        (tab) => tab.key === this.activeTab
      );
      if (activeIdx > 0) {
        // 保留首页和当前及其右侧
        this.tabs = this.tabs.filter(
          (tab, idx) => idx === 0 || idx >= activeIdx
        );
      }
    },
    closeRightTabs() {
      const activeIdx = this.tabs.findIndex(
        (tab) => tab.key === this.activeTab
      );
      if (activeIdx < this.tabs.length - 1) {
        // 保留首页和当前及其左侧
        this.tabs = this.tabs.filter(
          (tab, idx) => idx === 0 || idx <= activeIdx
        );
      }
    },
    cleanMenu() {
      this.menuList = [];
    },
    //获得最新菜单数据
    getLatestMenuList() {
      return new Promise(async (reslove: any, reject: any) => {
        try {
          const data = await getMenuList({});
          const menuData = buildTreeAndSort(_.cloneDeep(data));
          this.latestMenuList = [
            {
              parent_id: "",
              hidden: false,
              icon: "House",
              keepalive: false,
              component_name: "Index",
              component_src: "",
              directory: 1,
              weight: 1,
              menu_name: "首页",
              router_src: "/index",
              menu_id: "666",
              children: [],
            },
          ].concat(_.cloneDeep(menuData));
          //构建纯目录树形菜单数据
          const transformedData: any = transformMenuData(_.cloneDeep(menuData));
          this.setDirMenu(
            [
              {
                value: "-1",
                label: "根目录",
                children: [],
              },
            ].concat(transformedData)
          );
          reslove(true);
        } catch (error) {
          reject(error);
        }
      });
    },
    initEnteryMenuData(fullPath: string) {
      const matchedItem = this.flattenMenu.find(
        (item) => item.router_src == fullPath
      );
      if (matchedItem) {
        // console.log("找到了匹配的菜单项:", matchedItem);
        if (!this.tabs.find((tab: any) => tab.key === matchedItem.menu_id)) {
          this.setTabs({
            key: matchedItem.menu_id,
            label: matchedItem.menu_name,
            path: matchedItem.router_src,
            icon: matchedItem.icon,
            closeable: true,
          });
        }
        //激活的菜单
        this.setActiveMenu(matchedItem.menu_id);
        //激活的导航
        this.setActiveTab(matchedItem.menu_id);
        //展开的菜单
        this.setExpandedMenus(matchedItem.menu_id);
      } else {
        console.log("未找到匹配的菜单项");
      }
    },
    initMeun() {
      return new Promise(async (reslove: any, reject: any) => {
        try {
          console.log(this.user_info, "用户信息");
          const data = await getMenuList({
            roleId: this.user_info.roleId,
          });
          const menuData = buildTreeAndSort(_.cloneDeep(data));
          //构建纯目录树形菜单数据
          const transformedData: any = transformMenuData(_.cloneDeep(menuData));
          this.setDirMenu(
            [
              {
                value: "-1",
                label: "根目录",
                children: [],
              },
            ].concat(transformedData)
          );
          this.menuList = [
            {
              parent_id: "",
              hidden: false,
              icon: "House",
              keepalive: false,
              component_name: "Index",
              component_src: "",
              directory: 1,
              weight: 1,
              menu_name: "首页",
              router_src: "/index",
              menu_id: "666",
              children: [],
            },
          ].concat(_.cloneDeep(menuData));
          this.latestMenuList = _.cloneDeep(this.menuList);
          //获取所有vue文件
          const modules = import.meta.glob("/src/view/**/*.vue");
          //初始化路由
          generateRoutes(_.cloneDeep(menuData), modules);
          reslove(true);
        } catch (error) {
          console.log(error, "获取菜单失败");
          reject(false);
        }
      });
    },
  },
});
function transformMenuData(menuData: any) {
  return menuData
    .filter((item: any) => item.directory === 0)
    .map((item: any) => ({
      value: item.menu_id,
      label: item.menu_name,
      children:
        item.directory === 0 && item.children && item.children.length > 0
          ? transformMenuData(item.children)
          : [],
    }));
}
//组装菜单
function buildTreeAndSort(data: any, parentId = "", router_src = "") {
  // 过滤出当前parentId下的所有子项，并根据weight排序
  const children: any = data
    .filter((item: any) => Number(item.parent_id) === Number(parentId))
    .sort((a: any, b: any) => a.weight - b.weight);
  // 遍历这些子项，递归地构建它们的children属性
  return children.map((child: any) => {
    const path = router_src
      ? router_src + "/" + child.router_src
      : child.router_src;
    return {
      ...child,
      self_src: child.router_src, //保留数据库地址数据,解决历史遗留问题
      router_src: path, //这是拼接层级后访问路径
      children: buildTreeAndSort(_.cloneDeep(data), child.menu_id, path), // 递归调用以处理子项的子项
    };
  });
}
function generateRoutes(data: any, modules: any) {
  // console.log(data, modules);
  data.forEach((item: any) => {
    if (item.children.length > 0) {
      generateRoutes(item.children, modules);
    } else {
      if (item.directory != 0) {
        // console.log(`../view/${item.component_src}.vue`);
        router.addRoute("Home", {
          path: item.router_src,
          name: item.component_name,
          component: modules[`/src/view/${item.component_src}.vue`],
          meta: {
            title: item.menu_name,
            icon: item.icon,
            keepalive: item.keepalive,
            hidden: item.hidden,
            weight: item.weight,
            directory: item.directory,
          },
        });
      }
    }
  });
}
